﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using CurrentCostSystemTray.CurrentCostService;
using System.Threading;
using System.Collections;
using CurrentCostLibrary;

namespace CurrentCostSystemTray
{
    public class CurrentCostSystemTrayApp : Form
    {
        public static void Main()
        {
            Application.Run(new CurrentCostSystemTrayApp());
        }

        private NotifyIcon trayIcon;
        private ContextMenu trayMenu;
        

        private List<CurrentCostReading> readings = new List<CurrentCostReading>();
        bool isLive = true;


        private ContextMenu flashingLightMenu;
        private NotifyIcon flashingIcon;
        private int sleepTime = 0;
        

        public CurrentCostSystemTrayApp()
        {
            // Create a simple tray menu with only one item.
            trayMenu = new ContextMenu();
            trayMenu.MenuItems.Add("Exit", OnExit);

            flashingLightMenu = new ContextMenu();
            flashingIcon = new NotifyIcon();
            flashingIcon.ContextMenu = flashingLightMenu;
            

            // Create a tray icon. In this example we use a
            // standard system icon for simplicity, but you
            // can of course use your own custom icon too.
            trayIcon = new NotifyIcon();
            trayIcon.Text = "Getting energy data ...";
            trayIcon.Icon = new Icon(SystemIcons.Question, 40, 40);
            trayIcon.Click += new EventHandler(trayIcon_Click);

            // Add menu to tray icon and show it.
            trayIcon.ContextMenu = trayMenu;
            trayIcon.Visible = true;

            Thread updateThread = new Thread(RunUpdates);
            updateThread.Start();

            Thread flashThread = new Thread(FlashThread);
            flashThread.Start();



        }

        void trayIcon_Click(object sender, EventArgs e)
        {
            string target = "http://www.riotgibbon.org/weatherwcf/";
            System.Diagnostics.Process.Start(target);
        }

        public void FlashThread()
        {
            while (true)
            {
                if (sleepTime > 0)
                {
                    flashingIcon.Visible = true;
                    flashingIcon.Icon = new Icon(string.Format(@"Resources\red.ico"));
                    Thread.Sleep(sleepTime);
                    flashingIcon.Icon = new Icon(string.Format(@"Resources\black.ico")); 
                    Thread.Sleep (sleepTime);
                }
                else
                {
                    flashingIcon.Visible = false;
                }
            }
          

        }

        public void RunUpdates()
        {

            do
            {
                var client = new WeatherServiceClient();
                try
                {
                    client.Open();
                    var newReading = client.GetLastReading();
                    client.Close();


                    var ageOfReading = (int) DateTime.Now.Subtract( newReading.ReadingDateTime).TotalMinutes;
                    if (ageOfReading > 5)
                    {
                        if (isLive)
                        {
                            trayIcon.BalloonTipText = string.Format("No data received for {0} minutes", ageOfReading);
                            trayIcon.ShowBalloonTip(5000);
                            sleepTime = 0;
                        }
                        isLive = false;
                        
                    }
                    else if (!readings.Contains(newReading))
                    {
                        //set flashing icon interval
                        sleepTime = 500000 / newReading.Watts ;
                        if (!isLive)
                        {
                            trayIcon.BalloonTipText= string.Format("Back online");
                            trayIcon.ShowBalloonTip(5000);
                            
                        }
                        isLive =true;
                        readings.Add(newReading);
                        readings.RemoveAll(rd => rd.ReadingDateTime.Date != DateTime.Today);


                        int totalWatts = GetTotalWatts(readings);
                        var totalKWH = (double)totalWatts / 3600000;
                        double totalTime = readings.Last().ReadingDateTime.Subtract(readings.First().ReadingDateTime).TotalSeconds;

                        var average = (double)totalWatts / totalTime;


                        string newReadingText = string.Format("{0}W, {1}, Average: {2}, total {3} kWh", newReading.Watts, newReading.ReadingDateTime.ToLongTimeString(), average.ToString("0.0"), totalKWH.ToString("0.00"));
                        trayIcon.Text = newReadingText;

                        string iconName = string.Empty;

                        if (newReading.Watts < 50)
                        {
                            iconName = "level1";
                        }
                        else if (newReading.Watts >= 50 && newReading.Watts < 100)
                        {
                            iconName = "level2";
                        }
                        else if (newReading.Watts >= 100 && newReading.Watts < 150)
                        {
                            iconName = "level3";
                        }
                        else if (newReading.Watts >= 150 && newReading.Watts < 200)
                        {
                            iconName = "level4";
                        }
                        else if (newReading.Watts >= 200 && newReading.Watts < 250)
                        {
                            iconName = "level5";
                        }
                        else if (newReading.Watts >= 250 && newReading.Watts < 300)
                        {
                            iconName = "level6";
                        }
                        else if (newReading.Watts >= 300 && newReading.Watts < 400)
                        {
                            iconName = "level7";
                        }
                        else if (newReading.Watts >= 400 && newReading.Watts < 500)
                        {
                            iconName = "level8";
                        }

                        else if (newReading.Watts >= 500 && newReading.Watts < 750)
                        {
                            iconName = "level9";
                        }
                        else if (newReading.Watts >= 750 && newReading.Watts < 1000)
                        {
                            iconName = "level10";
                        }
                        else if (newReading.Watts >= 1000 && newReading.Watts < 1500)
                        {
                            iconName = "level11";
                        }
                        else if (newReading.Watts >= 1500 && newReading.Watts < 2000)
                        {
                            iconName = "level12";
                        }
                        else if (newReading.Watts >= 2000 && newReading.Watts < 3000)
                        {
                            iconName = "level13";
                        }

                        else if (newReading.Watts >= 3000)
                        {
                            iconName = "level14";
                        }

                        #region colours
                        //if (newReading.Watts < 100)
                        //{
                        //    iconName = "azure";
                        //}
                        //else if (newReading.Watts >= 100 && newReading.Watts < 200)
                        //{
                        //    iconName = "blue";
                        //}
                        //else if (newReading.Watts >= 200 && newReading.Watts < 400)
                        //{
                        //    iconName = "green";
                        //}
                        //else if (newReading.Watts >= 400 && newReading.Watts < 800)
                        //{
                        //    iconName = "orange";
                        //}
                        //else if (newReading.Watts >= 800 && newReading.Watts < 1200)
                        //{
                        //    iconName = "pink";
                        //}
                        //else if (newReading.Watts >= 1200 && newReading.Watts < 2000)
                        //{
                        //    iconName = "purple";
                        //}
                        //else if (newReading.Watts >= 2000 )
                        //{
                        //    iconName = "red";
                        //} 
                        #endregion



                        trayIcon.Icon = new Icon(string.Format(@"Resources\{0}.ico", iconName, 32, 32));
                    }
                }
                catch (Exception ex)
                {
                    client.Abort();
                    trayIcon.Icon = new Icon(SystemIcons.Error, 40, 40);
                    trayIcon.Text = string.Format("Error making reading");

                }
                Thread.Sleep(5000);
            } while (true);
        }

        private int GetTotalWatts(List<CurrentCostReading> readings)
        {
            CurrentCostReading lastReading;
            lastReading = readings[0];
            int totalJoules=0;
            foreach (var reading in readings)
            {
                var seconds = reading.ReadingDateTime.Subtract(lastReading.ReadingDateTime).TotalSeconds;
                var joules =(int) seconds * reading.Watts;
                totalJoules = totalJoules + joules;
                lastReading = reading;
            }
            var totalWatts = totalJoules;

    

            return totalWatts;
        }

        double GetTotalKWh(List<CurrentCostReading> readings)
        {
            int totalWatts = GetTotalWatts(readings);
            //3600000 joule = 1 kWh

            double totalKWh = (double) totalWatts / 3600000;
            return totalKWh;

        }



        protected override void OnLoad(EventArgs e)
        {
            Visible = false; // Hide form window.
            ShowInTaskbar = false; // Remove from taskbar.

            base.OnLoad(e);
        }

        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                // Release the icon resource.
                trayIcon.Dispose();
            }

            base.Dispose(isDisposing);
        }
    }
}
